import {Component, OnInit} from '@angular/core';
import {TableConfig} from "../../api-service/entity/table-config";
import {forkJoin, Observable} from "rxjs";
import {Order} from "../../api-service/entity/order";
import {CellClickedEvent, ColDef, GridReadyEvent, SelectionChangedEvent} from "ag-grid-community";
import {OrderDataService} from "../../api-service/order-data.service";
import {columnTypes, getColDefCustomType} from "../../utils/table.tools";
import {TableConfigService} from "../../api-service/table-config.service";

@Component({
  selector: 'app-custom-column-type',
  templateUrl: './custom-column-type.component.html',
  styleUrls: ['./custom-column-type.component.less']
})
export class CustomColumnTypeComponent implements OnInit {

  tableConfig: TableConfig[] = []
  orderList?: Observable<Order[]>
  colDef: ColDef[] = []
  defaultColDef: ColDef = {
    resizable: true
  }
  columnType: {[colType: string]: ColDef} = {}
  selectedRowIndex: (number | null)[] = []

  constructor(private orderDataService: OrderDataService, private tableConfigService: TableConfigService) { }

  ngOnInit(): void {
    forkJoin([
      this.tableConfigService.getTableConfig()
    ]).subscribe(([tableConfig]) => {
      this.tableConfig = tableConfig
      this.resolveTableConfig()
    })
    this.columnType = columnTypes()
  }

  // 转换表格配置数据
  resolveTableConfig() {
    this.colDef = []
    if (!this.tableConfig.length) {
      return
    }
    this.colDef = this.tableConfig.map(value => {
      return getColDefCustomType(value);
    })
  }

  getOrderData(): Observable<Order[]> {
    return this.orderDataService.getOrderList()
  }

  /**
   * 表格初始化成功
   * @param params
   */
  onGridReady(params: GridReadyEvent) {
    this.orderList = this.getOrderData()
  }

  /**
   * 单元格点击事件
   * @param e 点击的单元格
   */
  onCellClicked(e: CellClickedEvent) {
    console.log('cellClicked', e);
  }

  /**
   * 选中行变化了
   */
  onSelectionChanged(event: SelectionChangedEvent){
    // event.api.getSelectedNodes() 获取选中的row 数据，包含你提供给table的数据（row.data），和row 本身的一些数据
    // event.api.getSelectedRows() 获取选中的row 数据，仅包含你提供给table的数据，不包含row 本身的一些数据
    const nodes = event.api.getSelectedNodes()
    if (nodes && nodes.length) {
      this.selectedRowIndex = nodes.map(value => value.rowIndex)
    }else {
      this.selectedRowIndex = []
    }
  }

}
